from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKUImage, SKU
from apps.meiduo_admin.serializers.image import SKUImageSerializer, SKUSerializer
from apps.meiduo_admin.serializers.user import UserModelSerializer
from apps.meiduo_admin.utils import PageNum
from apps.users.models import Users


class SKUImageListView(ModelViewSet):
    # 指定查询集
    queryset = SKUImage.objects.all()

    # 指定序列化器
    serializer_class = SKUImageSerializer

    # 指定分页
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):

        image = request.data.get('image')
        sku_id = request.data.get('sku')

        image_data = image.read()

        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # todo 保存数据
        # 上传fdfs

        client = Fdfs_client('utils/fastdfs/client.conf')
        result = client.upload_by_buffer(image_data)

        if result.get("Status") != 'Upload successed':
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 图片上传成功
        file_id = result.get('Remote file_id')
        # 保存到数据库
        sku_image = SKUImage.objects.create(sku_id=sku_id, image=file_id)

        return Response({
            "id": sku_image.id,
            "image": sku_image.image.url
        }, status=status.HTTP_201_CREATED)


# 显示所有的SKU
class SKUListAPIView(ListAPIView):
    # 指定序列化器
    serializer_class = SKUSerializer
    # 查询集
    queryset = SKU.objects.all()
